<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use App\Exception\ValidateException;


class SmsAuthMiddleware implements MiddlewareInterface
{
	
	/**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;
	

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }
	
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
		$verify_id = $this->request->input('verify_id');
		$verify	= $this->request->input('verify');
		
		$mobile	= $this->request->input('mobile');
		if(empty($verify_id) || empty($verify)){
			throw new ValidateException("短信验证ID或者验证码不能为空");
		}
		$cacheData = cache()->get($verify_id);
		
		if($cacheData['code'] <> $verify){
			throw new ValidateException("验证码错误或者已过期");
		}
		
		if($cacheData['mobile'] <> $mobile){
			throw new ValidateException("手机号与验证不一致");
		}
		
        return $handler->handle($request);
    }
    
} 